<template>
  <div style="height: 100%;">
    <el-row :gutter="20" style="margin-left:0px;margin-right:0px;height: 100%;">
      <el-col :span="6" style="padding:0px;  height: 100%; border-right: 1px solid#ccc;">
        <!-- 组织机构树 -->
        <div class="zztree ">
          <div slot="header" class="clearfix zztree-title">
            <span class="span-title">组织机构树</span>
          </div>
          <div class="zztree-con tree-detail" style="height: 100%;overflow-y: auto;">
            <el-tree ref='treePart' :data="treeData"
                     :props="defaultProps"
                     v-loading="loading"
                     @node-click="handleNodeClick"
                     :expand-on-click-node='false'
                     node-key="id"
                     :highlight-current='true'
                     :default-expand-all='true'>
                        <span class="custom-tree-node" slot-scope="{ node, data }">
                          <span v-if="data.other.Status == 0" class="ztrrName" style="display: inline-block;" :title="data.name">{{ data.name }}</span>
                          <span v-if="data.other.Status == 1" class="ztrrName" style="display: inline-block;color:red" :title="data.name">{{ data.name }}(禁用)</span>
                        </span>
                     </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="18" style="padding:0px;height: 100%;">
        <div class="job-tab">
          <div slot="header" class="clearfix zztree-title">
            <span class="span-title">兼职列表</span>
          </div>
          <div style="margin-top:15px;">
            <div class=" select-container">
              <el-row class="">
                <el-col :span="24" class="">
                  <el-form ref="form" label-width="100px" label-position='right' size="small" :inline="true">
                    <el-col :span="4" style="">
                      <el-form-item label="" style="margin:12px 3px;">
                        <el-input prefix-icon="el-icon-search" placeholder="登录名称" v-model="listQuery.condition.loginName.value" clearable>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4" style="">
                      <el-form-item label="" style="margin:12px 3px;">
                        <el-input prefix-icon="el-icon-search" placeholder="用户名称" v-model="listQuery.condition.name.value" clearable>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <!-- 用户状态 -->
                      <el-form-item label="" style="margin:12px 0px;">
                        <el-select placeholder="请选择用户状态" v-model="listQuery.condition.status.value" clearable>
                          <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name" :value="item.key">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="10" style="padding-left:10px;margin-top:12px;float:right;margin-right:0">
                      <el-button size="small" style="height:30px;padding-top:0px;line-height:30px;" type="success" icon="el-icon-edit" @click="getList(selectOuinfoId,'find')">查 询</el-button>
                      <el-button size="small" style="height:30px;padding-top:0px;line-height:30px;" type="danger" icon="el-icon-circle-close-outline" @click="handleReset">重 置</el-button>
                      <el-button size="small" style="height:30px;padding-top:0px;line-height:30px;" type="primary" icon="el-icon-circle-plus-outline" @click="handleCreate">新建</el-button>
                    </el-col>
                  </el-form>
                </el-col>

              </el-row>
            </div>
          </div>
        </div>
        <div class="job-table">
          <el-table :key='tableKey' :data="list"
                    size="small"
                    height="320"
                    element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%">
            <el-table-column align="center" label="序号" width="50" type="index">
              <template slot-scope="scope">
              <span>{{scope.$index + (serialNumber - 1) * listQuery.rowBounds.limit + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="登录名称" width="100" prop="loginName">
              <template slot-scope="scope">
                <span>{{scope.row.loginName}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="用户名称" width="100" prop="name">
              <template slot-scope="scope">
                <span>{{scope.row.name}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="主部门" width="200" prop="orgName">
              <template slot-scope="scope">
                <span>{{scope.row.orgName}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="兼职部门" width="200" prop="compoundOrgname">
              <template slot-scope="scope">
                <span>{{scope.row.compoundOrgname}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="用户状态" width="100" prop="status">
              <template slot-scope="scope">
                <span>{{scope.row.status | statusFilter}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="是否用于身份切换" prop="status">
              <template slot-scope="scope">
                <span>{{scope.row.useIdentitySwitching | useIdentitySwitchingFilter}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操 作" width="160">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleEdit(scope.row)" style="width:30px;">编辑</el-button>
                <el-button type="text" size="small" @click="handleDelete(scope.row,'delete')" style="width:30px; margin-left:5px;">删除</el-button>
                <el-button type="text" size="small" @click="handleUserRole(scope.row)" style="width:60px; margin-left:5px;">配置角色</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="listQuery.page"
                           :page-sizes="[10,20,30, 50]" :page-size="listQuery.rowBounds.limit"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <!--菜单新增根节点弹出层-->
    <el-dialog
      v-if="dialogVisiblePartJob"
      :close-on-click-modal="false"
      @close="closeDialog"
      title="兼职新增(未设置用户)"
      :visible.sync="dialogVisiblePartJob"
      width="70%">
      <newPartJob :partJobData="partJobData" @changeCloseDialog="changeCloseDialog"></newPartJob>
    </el-dialog>
    <!--兼职详细弹出层-->
    <el-dialog v-if="ptDetailDialog"  :close-on-click-modal="false" title="兼职编辑"
               :visible.sync="ptDetailDialog" width="500px">
      <div>
        <div style="padding-bottom: 15px">
          <el-form ref="detailForm" :model="ptRecord" :rules="detailDialogRules" label-position="top" size="small"  label-width="110px">
            <el-row>
              <el-col>
                <el-form-item label="用户名称" prop="userName">
                  <el-input v-model="ptRecord.userName" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-form-item label="兼职机构" prop="orgName">
                  <el-input v-model="ptRecord.orgName" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-form-item label="是否用于身份切换" prop="useIdentitySwitching">
                  <el-select placeholder="请选择" v-model="ptRecord.useIdentitySwitching" clearable>
                    <el-option v-for="item in isInnerOption" :key="item.key" :label="item.display_name" :value="item.key">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div style="display: inline-block; width: 100%;text-align: right;">
          <el-button size="small" type="success" @click="doSaveDetail()">保存</el-button>
        </div>
      </div>
    </el-dialog>
    <!--编辑角色弹出层-->
    <el-dialog
      v-if="dialogVisibleEditUserRole"
      :close-on-click-modal="false"
      title="配置角色"
      :visible.sync="dialogVisibleEditUserRole"
      width="70%">
      <editUserRole :editUserRoleData="editUserRoleData"></editUserRole>
    </el-dialog>
  </div>
</template>

<script>
import { getOrgTree, compositeSelect, forceDeleteItem, updateItem } from '@/api/systemManage/partJobManagement'
import {
  statusOptions,
  statusKeyValue,
  isInnerOption,
  isInneNoKeyValue
} from '@/utils/allOptions'
import newPartJob from './newPartJob'
import editUserRole from '@/views/systemManage/commonComponents/userRole/editUserRole'
export default {
  components: {
    newPartJob,
    editUserRole
  },
  data() {
    return {
      dialogVisiblePartJob: false,
      dialogVisibleEditUserRole: false,
      partJobData: '',
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      editUserRoleData: {
        isPt: 1,
        userId: '',
        userOrgId: ''
      },
      loading: false,
      listQuery: {
        rowBounds: {
          offset: 0,
          limit: 10
        },
        condition: {
          pt: {
            property: 'pt',
            value: '1',
            type: 'EQ'
          },
          loginName: {
            property: 'loginName',
            value: '',
            type: 'LIKE'
          },
          name: {
            property: 'name',
            value: '',
            type: 'LIKE'
          },
          status: {
            property: 'status',
            value: '0',
            type: 'EQ'
          }
        },
        sort: [{
          direction: 'ASC',
          property: 'orderNo'
        }]
      },
      list: [],
      tableKey: 0,
      total: null,
      selectOuinfoId: '',
      selectItem: {
        'selectId': '',
        'selectOuinfoId': '',
        'selectOuinfoName': ''
      },
      statusOptions,
      isInnerOption,
      serialNumber: 1,
      ptDetailDialog: false,
      ptRecord: {
        orgId: '',
        orgName: '',
        userId: '',
        userName: '',
        useIdentitySwitching: ''
      },
      detailDialogRules: {
        useIdentitySwitching: [
          { message: '是否用于身份切换不能为空', required: true, trigger: 'change' }
        ]
      }
    }
  },
  filters: {
    statusFilter(target) {
      return statusKeyValue[target]
    },
    useIdentitySwitchingFilter(target) {
      return isInneNoKeyValue[target]
    }
  },
  methods: {
    changeCloseDialog() {
      this.dialogVisiblePartJob = false
      this.getList(this.selectOuinfoId)
    },
    handleNodeClick(data, node) {
      this.listQuery.rowBounds.offset = 0
      this.selectItem.selectOuinfoId = data.id
      this.$store.state.user.selectOrgId = data.id
      this.selectOuinfoId = data.id
      this.serialNumber = 1
      this.getList(data.id)
    },
    getTree() {
      this.loading = true
      const id = { id: this.$store.getters.orgId }
      getOrgTree(id).then(response => {
        this.treeData = response.data.data
        // 默认给个组织机构ID
        this.$nextTick(() => {
          this.$refs.treePart.setCurrentKey(this.$store.state.user.selectOrgId) // treeBox 元素的ref   value 绑定的node-key
        })
        if (this.$store.state.user.selectOrgId) {
          this.selectItem.selectOuinfoId = this.$store.state.user.selectOrgId
          this.selectOuinfoId = this.$store.state.user.selectOrgId
        } else {
          this.selectItem.selectOuinfoId = this.treeData[0].id
        }
        this.loading = false
        this.getList(this.selectItem.selectOuinfoId)
      })
    },
    handleCreate() {
      if (this.selectItem.selectOuinfoId) {
        this.partJobData = this.selectItem.selectOuinfoId
        this.dialogVisiblePartJob = true
        // this.$router.push({ name: 'newPartJob', params: { id: this.selectItem.selectOuinfoId }})
      } else {
        this.$message({
          message: '请选择组织机构。',
          type: 'warning'
        })
      }
    },
    handleEdit(row) {
      this.ptRecord.orgId = row.compoundOrgId
      this.ptRecord.orgName = row.compoundOrgname
      this.ptRecord.userId = row.id
      this.ptRecord.userName = row.name
      this.ptRecord.useIdentitySwitching = row.useIdentitySwitching
      this.ptDetailDialog = true
    },
    // 翻页器使用
    handleSizeChange(val) {
      this.listQuery.rowBounds.limit = val
      this.listQuery.rowBounds.offset = this.listQuery.rowBounds.limit * (this.serialNumber - 1)
      this.getList(this.selectItem.selectOuinfoId)
    },
    // 翻页器使用
    handleCurrentChange(val) {
      this.serialNumber = val
      this.listQuery.rowBounds.offset =
      // this.listQuery.rowBounds.limit * (val - 1) + 1
      this.listQuery.rowBounds.limit * (val - 1)
      this.getList(this.selectItem.selectOuinfoId)
    },
    getList(orgId, flag) {
      if (orgId) {
        this.listQuery.orgId = orgId
        if (flag === 'find') {
          this.listQuery.rowBounds.offset = 0
          this.total = 0
          this.serialNumber = 1
        }
        if (flag === 'delete') {
          if (this.listQuery.rowBounds.offset == (this.total - 1) &&
           this.listQuery.rowBounds.offset >= this.listQuery.rowBounds.limit) {
            this.listQuery.rowBounds.offset -= this.listQuery.rowBounds.limit
            this.serialNumber -= 1
          }
        }
        compositeSelect(this.listQuery).then(response => {
          this.list = response.data.data.records
          this.total = response.data.data.count
          this.listLoading = false
        })
      } else {
        this.$message({
          message: '请选择组织机构。',
          type: 'warning'
        })
      }
    },
    handleDelete(row, flag) {
      // console.log(row)
      this.$confirm(
        '此操作将删除【' + row.name + '】, 是否继续?',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          const data = {
            'userId': row.id,
            'orgId': row.compoundOrgId
          }
          forceDeleteItem(data).then(response => {
            if (response.data.statusCode === 200) {
              this.$message({
                message: '【' + row.name + '】已经被删除。',
                type: 'success'
              })
            } else {
              this.$message({
                message: response.data.message,
                type: 'error'
              })
            }
            this.$nextTick(() => {
              this.$refs.treePart.setCurrentKey(this.$store.state.user.selectOrgId) // treeBox 元素的ref   value 绑定的node-key
            })
            // this.handleReset()
            this.getList(this.selectItem.selectOuinfoId, flag)
          })
        })
        .catch(error => {
          console.error(error)
        })
    },
    handleUserRole(row) {
      this.editUserRoleData.userId = row.id
      this.editUserRoleData.userOrgId = row.compoundOrgId
      this.dialogVisibleEditUserRole = true
    },
    handleReset() {
      this.listQuery.condition.loginName.value = ''
      this.listQuery.condition.name.value = ''
      this.listQuery.condition.status.value = '0'
      this.listQuery.rowBounds.offset = 0
      this.listQuery.rowBounds.limit = 10
      this.list = null
      this.total = 0
      this.serialNumber = 1
      this.getTree()
    },
    closeDialog() {
      this.getList(this.selectOuinfoId)
    },
    doSaveDetail() {
      this.$refs['detailForm'].validate((valid) => {
        if (valid) {
          this.ptDetailDialog = false
          let data = {
            userId: this.ptRecord.userId,
            orgId: this.ptRecord.orgId,
            useIdentitySwitching: this.ptRecord.useIdentitySwitching
          }
          updateItem(data).then(response => {
            if (response.data && response.data.success) {
              this.getList(this.selectItem.selectOuinfoId)
              this.$message({
                message: '更新成功',
                type: 'success'
              })
            } else {
              this.$message({
                message: '添加失败',
                type: 'error'
              })
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: '数据验证失败!'
          })
          return false
        }
      })
    }
  },
  mounted() {
    this.getTree()
  }
}
</script>

<style scoped>
  .text {
    font-size: 14px;
  }
.select-container{
    padding: 10px 10px;
    margin-bottom: 10px;
    margin-left: 3px;
    margin-right: 3px;
    border-radius: 4px;
    border: 1px solid #eeeeee;
  }
  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both;
  }

  .box-card {
    width: 100%;
  }

  .el-button--mini,
  .el-button--mini.is-round {
    padding: 3px 5px;
  }
  .span-title{
    float: left;
    line-height: 16px;
    border-left:4px solid #000;
    padding-left: 10px;
    font-size: 16px;
    margin-top: 7px;
  }
</style>
